kotlin宣告class方式與java一樣
class Invoice {
}
kotlin的class會有一個primary constructor
以及一個或多個的secondary constructors
primary constructor主要寫在class name後方
class Person constructor(firstName: String) {
}
如果primary constructor沒有任何的annotations
constructor關鍵字可省略
class Person(firstName: String) {
}
primary constructor內不可包含任何code
想要初始化的話可以寫在 init{...} 內
class InitOrderDemo(name: String) {
init {
println("hello"+name)
}
}
primary constructor的參數初始化可在init{}
class Customer(name: String) {
val customerKey = name.toUpperCase()
}
或者有更簡潔的寫法
class Person(val firstName: String, val lastName: String, var age: Int) {
// ...
}
如果沒宣告成變數 在class內部會編譯錯誤
使用constructor 宣告secondary constructors
class Person {
constructor(parent: Person) {
parent.children.add(this)
}
}
如果class有primary constructor
則secondary constructors需要透過this直接或間接的呼叫primary constructor
class Person(val name: String) {
constructor(name: String, parent: Person) : this(name) {
parent.children.add(this)
}
}